'''
Created on Jun 20, 2012

@author: alebalbin
'''
from collections import defaultdict
#from base import gtf_transcript


class gtf_transcript():
    
    
    def __init__(self,fields):
        self.annotation=defaultdict()
        self.chrom=fields[0]
        self.feature=fields[1] 
        self.feature_type=fields[2]
        self.start=fields[3]
        self.end=fields[4]
        self.atributte1=fields[5]
        self.strand=fields[6]
        self.atribute2=fields[7]
        for a in fields[-1].split(';'):
            if a=='':
                continue
            att, value= a.split()[0].strip(),a.split()[1].strip()
            self.annotation[att]=value
        self.returnme()
    def returnme(self):
        return self


def read_gtf_entry(line, transc_types=None,filter_transc=False):
    '''
    1    protein_coding    CDS    65882    65971    .    +    0    exon_number "1"; gene_id "ENSG00000186092"; gene_name "OR4F5"; p_id "P16283"; protein_id "ENSP00000440176"; transcript_id "ENST00000534990"; transcript_name "OR4F5-201"; tss_id "TSS9774";
    1    protein_coding    exon    65882    65971    .    +    .    exon_number "1"; gene_id "ENSG00000186092"; gene_name "OR4F5"; p_id "P16283"; transcript_id "ENST00000534990"; transcript_name "OR4F5-201"; tss_id "TSS9774";
    '''
    # Classes of transcripts to be first considered    
    trtype=1
    fields = line.strip('\n').split('\t')
    if filter_transc and (transc_types is not None):
        if (fields[trtype] in transc_types):
            return gtf_transcript(fields)
    if not filter_transc:
        return gtf_transcript(fields)
    else:
        return None
    
def read_gtf(gtf_file):
    transcripts=['lincRNA','protein_coding','misc_RNA',
                 'polymorphic_pseudogene','misc_RNA_pseudogene',
                 'pseudogene', 'miRNA', 'processed_transcript',
                 'miRNA_pseudogene']
    filter=True
    for line in gtf_file:
        t = read_gtf_entry(line,transcripts,filter)
        if t is not None:
            yield t